package flc.ast.activity;

import static com.stark.imgedit.ImgEditActivity.MODE_COLOR_TUNE;
import static com.stark.imgedit.ImgEditActivity.MODE_CROP;
import static com.stark.imgedit.ImgEditActivity.MODE_FILTER;
import static com.stark.imgedit.ImgEditActivity.MODE_NONE;
import static com.stark.imgedit.ImgEditActivity.MODE_ROTATE;

import static flc.ast.utils.Content.BANK_CARD_REC;
import static flc.ast.utils.Content.BUSINESS_LICENSE_REC;
import static flc.ast.utils.Content.CLIPS_REQ;
import static flc.ast.utils.Content.ID_CARD_REC;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.FragmentTransaction;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.graphics.RectF;
import android.os.Bundle;
import android.view.View;

import com.blankj.utilcode.util.CollectionUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.github.chrisbanes.photoview.PhotoView;
import com.stark.imgedit.fliter.PhotoProcessing;
import com.stark.imgedit.view.CropImageView;
import com.stark.imgedit.view.RotateImageView;

import java.util.ArrayList;
import java.util.List;

import flc.ast.BaseAc;
import flc.ast.R;
import flc.ast.databinding.ActivitySingleResultBinding;
import flc.ast.fragment.AdjustFragment;
import flc.ast.fragment.BaseEditFragment;
import flc.ast.fragment.FilterFragment;
import flc.ast.utils.Content;
import io.reactivex.rxjava3.core.ObservableEmitter;
import stark.common.basic.constant.Extra;
import stark.common.basic.event.EventStatProxy;
import stark.common.basic.utils.IntentUtil;
import stark.common.basic.utils.RxUtil;

public class SingleResultActivity extends BaseAc<ActivitySingleResultBinding> {

    private static Bitmap sSpecialEffectBmp;
    private static boolean isEdit;//是否为图片编辑进入

    public int mode = MODE_NONE;// 当前操作模式
    public PhotoView mImgView;

    private Bitmap mRetBitmap;
    private Bitmap mNoFilterEditBitmap;
    private Bitmap mHasFilterBitmap;
    public RotateImageView mRotateView;
    public CropImageView mCropView;
    public boolean mHasOriginFilter;
    private boolean mHasClickEdit;

    private AdjustFragment mAdjustFragment;
    private FilterFragment mFilterFragment;


    public static void start(Activity activity, Bitmap resultBitmap) {
        Intent intent = IntentUtil.getIntent(activity, SingleResultActivity.class);
        sSpecialEffectBmp = resultBitmap;
        isEdit = false;
//        intent.putExtra(Extra.CODE, reqCode);
//        activity.startActivityForResult(intent, reqCode);
        activity.startActivity(intent);
    }

    public static void start(Activity activity, Bitmap resultBitmap, boolean edit) {
        Intent intent = IntentUtil.getIntent(activity, SingleResultActivity.class);
        sSpecialEffectBmp = resultBitmap;
        isEdit = edit;
        activity.startActivity(intent);
    }


    public Bitmap getMainBit() {
        return mRetBitmap;
    }

    public Bitmap getmNoFilterEditBitmap() {
        return mNoFilterEditBitmap;
    }

    public Bitmap getmHasFilterBitmap() {
        return mHasFilterBitmap;
    }

    private void setFilter(final int f) {
        showDialog(getString(com.stark.common.res.R.string.handling));
        RxUtil.create(new RxUtil.Callback<Bitmap>() {
            @Override
            public void doBackground(ObservableEmitter<Bitmap> emitter) {
                Bitmap retBitmap;
                retBitmap = Bitmap.createBitmap(mNoFilterEditBitmap.copy(Bitmap.Config.ARGB_8888, true));
                PhotoProcessing.filterPhoto(retBitmap, f);
                emitter.onNext(retBitmap);
            }

            @Override
            public void accept(Bitmap bitmap) {
                dismissDialog();
                if (bitmap == null) {
                    return;
                }
                mRetBitmap = bitmap;
                mHasFilterBitmap = bitmap;
                mDataBinding.imageViewTouch.setImageBitmap(bitmap);
//                mDataBinding.imageViewTouch.setDisplayType(ImageViewTouchBase.DisplayType.FIT_TO_SCREEN);

            }
        });
    }

    @Override
    protected int onCreate() {
        return R.layout.activity_single_result;
    }

    @Override
    protected void initView() {
        EventStatProxy.getInstance().statEvent1(this, mDataBinding.event1Container);

        mDataBinding.ivSingleResultBack.setOnClickListener(v -> onBackPressed());

        mHasClickEdit = false;
        mHasOriginFilter = false;
        mImgView = mDataBinding.imageViewTouch;
        mRotateView = mDataBinding.rotateImgView;

        mDataBinding.tvRotate.setOnClickListener(this);
        mDataBinding.tvAdjust.setOnClickListener(this);
        mDataBinding.tvCrop.setOnClickListener(this);
        mDataBinding.tvFilter.setOnClickListener(this);
        mDataBinding.tvSave.setOnClickListener(this);
        mDataBinding.ivClose.setOnClickListener(this);
        mDataBinding.ivRight.setOnClickListener(this);

        mNoFilterEditBitmap = sSpecialEffectBmp;
        mRetBitmap = sSpecialEffectBmp;
        setFilter(2);
    }

    @Override
    protected void onClickCallback(View v) {
        switch (v.getId()) {
            case R.id.tvRotate://旋转
                saveRotateImage();
                break;
            case R.id.tvCrop://裁剪
                ClipsActivity.sHasOriginFilter = mHasOriginFilter;
                ClipsActivity.sNoFilterEditBitmap = mNoFilterEditBitmap;
                ClipsActivity.sHasFilterBitmap = mHasFilterBitmap;
                Intent intent = new Intent(mContext, ClipsActivity.class);
                startActivityForResult(intent, CLIPS_REQ);
                break;
            case R.id.tvFilter://滤镜
                if (!mHasClickEdit) {
                    mHasClickEdit = true;
                    mDataBinding.tvFilter.setSelected(true);
                    mDataBinding.tvAdjust.setSelected(false);
                    mDataBinding.tvRotate.setSelected(false);
                    mDataBinding.tvCrop.setSelected(false);
                    mDataBinding.llModify.setVisibility(View.VISIBLE);
                    mDataBinding.tvSave.setVisibility(View.GONE);
                    showFilterListFragment();
                } else {
                    ToastUtils.showShort(R.string.no_commit_edit_tips);
                }
                break;
            case R.id.tvAdjust://调节
                if (!mHasClickEdit) {
                    mHasClickEdit = true;
                    mDataBinding.tvFilter.setSelected(false);
                    mDataBinding.tvAdjust.setSelected(true);
                    mDataBinding.tvRotate.setSelected(false);
                    mDataBinding.tvCrop.setSelected(false);
                    mDataBinding.llModify.setVisibility(View.VISIBLE);
                    mDataBinding.tvSave.setVisibility(View.GONE);
                    showColorTuneFragment();
                } else {
                    ToastUtils.showShort(R.string.no_commit_edit_tips);
                }
                break;
            case R.id.ivClose://取消
                closeModifyState();
                break;
            case R.id.ivRight://确定
                clickApply();
                break;
            case R.id.tvSave://完成
                ScanPreviewActivity.sBitmap = mRetBitmap;
                startActivity(ScanPreviewActivity.class);
                break;
        }
    }

    @Override
    protected void initData() {
        if (isEdit) {
            mDataBinding.tvSingleResultTitle.setText(getString(R.string.img_edit));
        } else {
            mDataBinding.tvSingleResultTitle.setText(getString(R.string.shot_scan));
        }
    }

    /**
     * 点击右下角“勾”后的处理
     */
    private void clickApply() {
        showFunc();
        mDataBinding.flFragmentContainer.setVisibility(View.INVISIBLE);
        switch (mode) {
            case MODE_FILTER:
                mFilterFragment.applyFilterImage();
                return;
            case MODE_COLOR_TUNE:
                mAdjustFragment.applyColorTune();
                return;
            default:
                break;
        }
    }

    private void showColorTuneFragment() {
        if (mAdjustFragment == null) {
            mAdjustFragment = AdjustFragment.newInstance();
        } else {
            mAdjustFragment.onShow();
        }
        showFragment(mAdjustFragment);
    }

    private void showFilterListFragment() {
        if (mFilterFragment == null) {
            mFilterFragment = FilterFragment.newInstance();
        } else {
            mFilterFragment.onShow();
        }
        showFragment(mFilterFragment);
    }

    private void showFragment(BaseEditFragment baseEditFragment) {
        mDataBinding.flFragmentContainer.setVisibility(View.VISIBLE);
        FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
        fragmentTransaction.replace(R.id.flFragmentContainer, baseEditFragment);
        fragmentTransaction.commitAllowingStateLoss();
    }

    private void closeModifyState() {
        showFunc();
        mDataBinding.flFragmentContainer.setVisibility(View.INVISIBLE);
        switch (mode) {
            case MODE_FILTER:
                mFilterFragment.backToMain();
                return;
            case MODE_COLOR_TUNE:
                mAdjustFragment.backToMain();
                return;
            default:
                break;
        }
    }

    public void showFunc() {
        mDataBinding.tvAdjust.setSelected(false);
        mDataBinding.tvFilter.setSelected(false);
        mDataBinding.llModify.setVisibility(View.GONE);
        mDataBinding.tvSave.setVisibility(View.VISIBLE);
        mHasClickEdit = false;
    }

    public void changeMainBitmap(Bitmap newBit, Bitmap filterBitmap, boolean needPushUndoStack) {
        if (newBit == null) return;
        mNoFilterEditBitmap = newBit;
        mHasFilterBitmap = filterBitmap;
        if (mHasOriginFilter) {
            mRetBitmap = newBit;
            mImgView.setImageBitmap(mRetBitmap);
        } else {
            mRetBitmap = filterBitmap;
            mImgView.setImageBitmap(mRetBitmap);
        }
//        mImgView.setDisplayType(ImageViewTouchBase.DisplayType.FIT_TO_SCREEN);

    }

    private void saveRotateImage() {
        mRotateView.addBit(getMainBit(),
                mImgView.getDisplayRect());
        mRotateView.reset();
        mRotateView.rotateImage(90);

        showDialog(getString(com.stark.common.res.R.string.handling));
        RxUtil.create(new RxUtil.Callback<List<Bitmap>>() {
            @Override
            public void doBackground(ObservableEmitter<List<Bitmap>> emitter) {
                RectF imageRect = mRotateView.getImageNewRect();
                Bitmap originBit;
                Bitmap filterBit;
                List<Bitmap> resultBitmap = new ArrayList<>();
                originBit = getmNoFilterEditBitmap();
                filterBit = getmHasFilterBitmap();
                Bitmap result1 = corpBit(imageRect, originBit);
                Bitmap result2 = corpBit(imageRect, filterBit);
                resultBitmap.add(result1);
                resultBitmap.add(result2);


                emitter.onNext(resultBitmap);
            }

            @Override
            public void accept(List<Bitmap> bitmap) {
                dismissDialog();
                if (CollectionUtils.isEmpty(bitmap)) return;
                changeMainBitmap(bitmap.get(0), bitmap.get(1), true);
                mImgView.setImageBitmap(getmHasFilterBitmap());
            }
        });
    }

    private Bitmap corpBit(RectF imageRect, Bitmap originBit) {
        Bitmap result = Bitmap.createBitmap((int) imageRect.width(), (int) imageRect.height(), Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(result);
        int w = originBit.getWidth() >> 1;
        int h = originBit.getHeight() >> 1;
        float centerX = imageRect.width() / 2;
        float centerY = imageRect.height() / 2;

        float left = centerX - w;
        float top = centerY - h;

        RectF dst = new RectF(left, top, left + originBit.getWidth(), top + originBit.getHeight());
        canvas.save();
        //bug fixed  应用时不需要考虑图片缩放问题 重新加载图片时 缩放控件会自动填充屏幕
        canvas.scale(mRotateView.getScaleX(), mRotateView.getScaleY(), imageRect.width() / 2, imageRect.height() / 2);
        canvas.rotate(mRotateView.getRotateAngle(), imageRect.width() / 2, imageRect.height() / 2);

        canvas.drawBitmap(originBit, new Rect(0, 0, originBit.getWidth(), originBit.getHeight()), dst, null);
        canvas.restore();
        return result;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == CLIPS_REQ) {
                changeMainBitmap(ClipsActivity.sNoFilterEditBitmap, ClipsActivity.sHasFilterBitmap, true);
            }
        }
    }
}